﻿using System;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;

namespace TotalFreedomKO
{
    /// <summary>
    /// Extensions for HtmlHelper 
    /// </summary>
    public static class KoInclude
    {
        #region template
       

        public static MvcHtmlString KoIncludeTemplate<T>(this HtmlHelper htmlHelper, string templateName) where T: IKoViewModel
        {
            return KoIncludeTemplate<T>(htmlHelper, templateName, htmlHelper.ViewData);
        }

        public static MvcHtmlString KoIncludeTemplate<T>(this HtmlHelper htmlHelper, string templateName, ViewDataDictionary viewData) where T : IKoViewModel
        {
            if (String.IsNullOrWhiteSpace(templateName))
                throw (new ArgumentException("Template name must be specified"));

            string templateId;
            if (templateName.StartsWith("_"))
                templateId = templateName.Substring(1);
            else
                templateId = templateName;

            string s = "<script type=\"text/html\" id=\"" + HttpUtility.HtmlAttributeEncode(Regex.Replace(templateId, "[^a-zA-Z0-9_]", "")) + "\">";
            s += htmlHelper.Partial(templateName, System.Activator.CreateInstance<T>(), viewData).ToHtmlString();
            s += "</script>";

            return MvcHtmlString.Create(s);
        }

        #endregion

        public static MvcHtmlString KoIncludeViewModel<T>(this HtmlHelper htmlHelper, T viewModel, string viewModelName = null) where T: IKoViewModel
        {
            if (String.IsNullOrWhiteSpace(viewModelName))
            {
                viewModelName = typeof(T).Name;
            }

            string viewModelFirstLower = viewModelName.Length > 0 ? (viewModelName.Substring(0,1).ToLower() + viewModelName.Substring(1)) : "";

            if (viewModelName == viewModelFirstLower)
                viewModelName += "Class";            

            StringBuilder sb = new StringBuilder();

            sb.AppendLine("<script type=\"text/javascript\">");
            sb.AppendLine("function " + HttpUtility.HtmlEncode(viewModelName) + "() {");
            sb.AppendLine("}");
            sb.AppendLine("var " + HttpUtility.HtmlEncode(viewModelFirstLower) + " =  new " + HttpUtility.HtmlEncode(viewModelName) + "();");
            sb.AppendLine("</script>");

            return new MvcHtmlString(sb.ToString());
        }
    }
}
